layui.use(['form','layer','laydate','table','laytpl'],function(){
    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        laydate = layui.laydate,
        laytpl = layui.laytpl,
        table = layui.table;
    //新闻列表
    var tableIns = table.render({
        elem: '#newsList',
        url : '/api/article/index',
        cellMinWidth : 95,
        page : true,
        height : "full-125",
        limit : 20,
        limits : [10,15,20,25],
        id : "newsListTable",
        cols : [[
            {type: "checkbox", fixed:"left", width:50},
            {field: 'id', title: 'id', width:60, align:"center"},
            {field: 'title', title: '文章标题', width:150},
            {field: 'author', title: '发布者', align:'center'},
            {field: 'status', title: '发布状态',  align:'center',templet:"#newsStatus"},
            {field: 'openness', title: '浏览权限', align:'center',templet:function(d){
                    return '<input type="checkbox" name="openness" lay-filter="openness" lay-skin="switch" lay-text="公开|私有" checked="'+d.openness+'">'
            }},
            {field: 'is_top', title: '是否置顶', align:'center', templet:function(d){

                return '<input type="checkbox" name="is_top" lay-filter="is_top" lay-skin="switch" lay-text="是|否" checked="'+d.is_top+'">'
            }},
            {field: 'created_at', title: '发布时间', align:'center', minWidth:110, templet:function(d){
                // return d.newsTime.substring(0,10);
                    return d.newTime;
            }},
            {title: '操作', width:170, templet:'#newsListBar',fixed:"right",align:"center"}
        ]]
    });

    //是否公开
    form.on('switch(openness)', function(data){
        //var index = layer.msg('修改中，请稍候',{icon: 16,time:false,shade:0.8});
        setTimeout(function(){
            if(data.elem.checked){
                winui.window.msg('设为公开成功');
            }else{
                winui.window.msg('设为私有成功');
            }
        },500);
    })
    //是否置顶
    form.on('switch(is_top)', function(data){
        var index = winui.window.msg('修改中，请稍候',{icon: 16,time:false,shade:0.8});
        setTimeout(function(){
            if(data.elem.checked){
                winui.window.msg('启动置顶成功');
            }else{
                winui.window.msg('取消置顶成功');
            }
        },500);
    })
    //搜索【此功能需要后台配合，所以暂时没有动态效果演示】
    $(".search_btn").on("click",function(){
        serialize=$('.layui-form').serializeArray();
        if($(".searchVal").val() != ''){
            table.reload("newsListTable",{
                page: {
                    curr: 1 //重新从第 1 页开始
                },
                where: {
                    key: serialize  //搜索的关键字
                }
            })
        }else{
            winui.window.msg("请输入搜索的内容");
        }
    });

    //添加文章
    function addNews(edit=null){
        if(!edit){
            var edit={
                'id':''
            };
        }
           winui.window.open({
           id: '公告',
           type: 2,
           title: '添加文章',
           content: "/admin/article/add?id="+edit.id,
           success:function(layero, index){
              var obj=layero.find("iframe")[0].contentWindow;


              if(edit.id && typeof obj.$=="function"){

                  obj.$('#title').val(edit.title);
                  obj.$('#keywords').val(edit.keywords);
                  obj.$('#conver').val(edit.cover);
                  obj.$('#srcimgurl').attr('src',edit.cover);
                  obj.$('input[id=openness][value='+edit.openness+']').attr('checked','checked');
                  obj.$("select[name=status]").val(edit.status);
                  if(edit.is_top==0){
                      obj.$('input[id=is_top]').attr('checked',false);
                  }else{
                      obj.$('input[id=is_top]').attr('checked',true);
                  }

                  if(edit.tag_ids){
                      if(edit.tag_ids.substring(edit.tag_ids.length,1)==","){
                          edit.tag_ids=edit.tag_ids.substr(0,edit.tag_ids.length-1);
                      }
                      obj.$('#tag_ids').val(edit.tag_ids);
                      tag_ids=edit.tag_ids.split(',');
                      var html='';

                      var name='';
                      $.each(tag_ids,function(key,value){
                          name='';
                          obj.$(".Ms-labe-backstageBtn").each(function(index,item){
                              if($(item).data('id')==value){
                                  name=item.innerHTML;
                              }
                          })
                          html+='<button type="button" class="layui-btn layui-btn-sm layui-btn-normal Ms-labe-box">' +
                              '<em>'+name+'</em>' +
                              '<i class="layui-icon layui-icon-close Ms-labe-Remove" data-id="'+value+'" style="color:red">X</i>' +
                              '</button>';
                          console.log(html);
                      })
                      obj.$('.Ms-labe-inner').html(html);
                  }
                  obj.$('input[id=type_id][value='+edit.type_id+']').attr('checked','checked');
                  obj.layui.form.render();
                  obj.layui.form.on("submit(addNews)",function(data) {
                      data.field['id']=edit.id;
                      $.post("/admin/article/store",data.field,function(data1){
                          winui.window.msg(data1.msg);
                          layer.close(index);
                          layero.find('.layui-layer-ico.layui-layer-close').trigger('click');
                          if(data1.code==1){
                              setTimeout(function(){
                                  tableIns.reload();
                              },250)
                          }
                      })
                  });
              }

                // setTimeout(function(){
                //     layui.layer.tips('点击此处返回文章列表', '.layui-layer-setwin .layui-layer-close', {
                //         tips: 3
                //     });
                // },500)
            }
        });
    }
    $(".addNews_btn").click(function(){
        addNews();
    })

    //批量删除
    $(".delAll_btn").click(function(){

        var checkStatus = table.checkStatus('newsListTable'),
            data = checkStatus.data,
            newsId = [];
        if(data.length > 0) {
            for (var i in data) {
                newsId.push(data[i].id);
            }
            var data={'ids':newsId};
            winui.window.confirm('确定删除选中的文章？', {icon: 3, title: '提示信息'}, function (index) {
                winui.window.post("/admin/article/del",data,function(data){
                    winui.window.msg(data.msg);
                    tableIns.reload();
                    //layer.close(index);
                })
                // })
            })
        }else{
            winui.window.msg("请选择需要删除的文章");
        }
    })

    //列表操作
    table.on('tool(newsList)', function(obj){
        var layEvent = obj.event,
            data = obj.data;

        if(layEvent === 'edit'){ //编辑
            addNews(data);

        } else if(layEvent === 'del'){ //删除
            data={'ids':data.id};
            winui.window.confirm('确定删除此文章？',{icon:3, title:'提示信息'},function(index){
            winui.window.post("/admin/article/del",data,function(data){
                console.log(data);
                winui.window.msg(data.msg);
                tableIns.reload();
                //layer.close(index);
            })
                // $.get("删除文章接口",{
                //     newsId : data.newsId  //将需要删除的newsId作为参数传入
                // },function(data){
                //     tableIns.reload();
                //     layer.close(index);
                // })
            });
        } else if(layEvent === 'look'){ //预览
            winui.window.alert("此功能需要前台展示，实际开发中传入对应的必要参数进行文章内容页面访问")
        }
    });

})